package com.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitterReturnValueHandler;

import com.alibaba.fastjson.JSON;
import com.common.MyThread;
import com.model.Thrd;
import com.model.Imitate;
import com.model.Jsoner;
import com.model.Seleniumtest;
import com.model.Threadhelper;
import com.service.SlnmServiceI;
import com.service.ThrdServiceI;
import com.sun.accessibility.internal.resources.accessibility_zh_CN;
import com.sun.tools.javah.Util.Exit;
import com.test.Testx;

import com.model.Zsxm;


@Controller
@RequestMapping("/thrdController")
public class ThrdController {
	
	private SlnmServiceI slnmService;

	public SlnmServiceI getSlnmService() {
		return slnmService;
	}
	@Autowired
	public void setSlnmService(SlnmServiceI slnmService) {
		this.slnmService = slnmService;
	}


	private ThrdServiceI thrdService;

	public ThrdServiceI getThrdService() {
		return thrdService;
	}
	
	@Autowired
	public void setThrdService(ThrdServiceI thrdService) {
		this.thrdService = thrdService;
	}



	@ResponseBody
	@RequestMapping("/getThrd")
	public String showThrd(String thrdid,HttpServletRequest request){
		
		Thrd thrd=thrdService.getThrdByThrdid(Integer.valueOf(thrdid));
		return JSON.toJSONString(thrd);
	}
	
	@ResponseBody
	@RequestMapping("/getthrdstat")
	public String getthrdstat(String thrdnm,HttpServletRequest request){
		
		Thrd thrd=thrdService.getThrdByThrdid(1);
		
		Threadhelper th=new Threadhelper();
		
		boolean rslt_thrd=th.compareThreadname(thrd.getThrdnm());
		
		
		if(rslt_thrd==false||thrd.getThrdflag()==false){
			rslt_thrd=false;
		}
		

		Jsoner jsoner=new Jsoner();
		String rslt=jsoner.createok("ok", JSON.toJSONString(rslt_thrd), "msg");
		
		return rslt;
	}
	
	@ResponseBody
	@RequestMapping("/start")
	public void start(HttpServletRequest request){
		
		Thrd thrd=thrdService.getThrdByThrdid(1);
		
		String thrdnm=Thread.currentThread().getName();
		thrd.setThrdnm(thrdnm);
		thrd.setThrdflag(true);
		thrdService.updatethrd(thrd);
		
		System.out.println("咫尺天涯的第一个线程(Thread)启动了。。。"); 
		
		//Selenium
		Imitate im=new Imitate();
		Date date=new Date();
		DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time=format.format(date);
		System.out.println("进入了新建profile");
		System.setProperty("webdriver.firefox.bin","C:/Program Files/Mozilla Firefox/firefox.exe");
        ProfilesIni allProfiles=new ProfilesIni();
        FirefoxProfile profile=allProfiles.getProfile("default");
		WebDriver driver = new FirefoxDriver(profile);
		String url_prx="http://112.124.32.145/zsxt/admin.php";
		int count_fail_connect=0;
		while(true){
        	thrd=thrdService.getThrdByThrdid(1);
//        	System.out.println(thrd.getThrdflag());
        	if(thrd.getThrdflag()==false){
        		try {
        			System.out.println("停止");driver.close();break;
//					Thread.currentThread().stop();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        		break;
        	}
//            System.out.println("系统默认的线程名字: aaaaa,自定义线程名字: "  + Thread.currentThread().getName() +",当前秒: " + new Date().getSeconds());  
            
        	
        	if(count_fail_connect>=5){break;}
        	
            //开始selenium
          //获取zsxmls
            
    		String zsxmls_json=im.sendGET(url_prx+"/If/getzsxmlsfoujiesuan", "");
    		
    		List<Zsxm> zsxmls=JSON.parseArray(zsxmls_json,Zsxm.class);
    		
    		for(int i=0;i<zsxmls.size();i++){
    			Zsxm zsxmv=zsxmls.get(i);
    			String url=zsxmv.getZsxmyhq();
    			try{
		        	driver.get(url);
		        	im.sleep(5000);
		        	WebElement we = driver.findElement(By.className("sale-info"));
		        	String str="";
		        	if(we.getText().indexOf("过期")==-1){
		        		String left=we.getText().split("张（已领用")[0].split("剩")[1].trim();
		        		String yilingyong=we.getText().split("（已领用")[1].split("张）")[0].trim();
		        		int sum=Integer.valueOf(left)+Integer.valueOf(yilingyong);
		        		
		        		str=java.net.URLEncoder.encode("已领用"+yilingyong+"/总"+sum,"utf-8");
		        	}else{
		        		//过期了，就要访问接口，更改数据
		        		str=java.net.URLEncoder.encode("不存在或过期","utf-8");
		        	}
		        	String paras="zsxmid="+zsxmv.getZsxmid()+"&yhqnum="+str;
		        	im.sendGET(url_prx+"/If/updateyhqnum", paras);
		        }catch(Exception e){
		        	System.out.println("访问失败"+url+time);
		        	count_fail_connect++;
		        	if(count_fail_connect>=5){stop(request);driver.close();break;}
		        	continue;
		        }
    			
    		}
            
    		
            
            
            
            try {  
                Thread.sleep(5000);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }
        	
            
            
        }  
        
        
	}
	
	
	
	@ResponseBody
	@RequestMapping("/stop")
	public void stop(HttpServletRequest request){
		
		Thrd thrd=thrdService.getThrdByThrdid(1);
		
		thrd.setThrdflag(false);
		thrdService.updatethrd(thrd);
		
//		Threadhelper th=new Threadhelper();
//		boolean rslt_thread=th.stopByThredname(thrd.getThrdnm());
		
		
		
//		Jsoner jsoner=new Jsoner();
//		String rslt=jsoner.createok("ok", JSON.toJSONString(rslt_thread), "msg");
		
//		return rslt;
	}
	
	
	@ResponseBody
	@RequestMapping("/getallthrd")
	public String getallthrd(HttpServletRequest request){
		
		Threadhelper th=new Threadhelper();
		
		String rslt_thrd=th.getallthrd();
		

		Jsoner jsoner=new Jsoner();
		String rslt=jsoner.createok("ok", JSON.toJSONString(rslt_thrd), "msg");
		
		return rslt;
	}
	
	
}
